import React, { Component } from 'react';
import {
	Route,
	Switch
} from 'react-router-dom'
import {
	connect,
	ConnectedProps
} from 'react-redux'
import { mainRoutes } from './routes'
import { Frame, NotFound } from './components'
import { checkSessionReq } from './requests/login'
import { loginSuccess } from './actions/loginAction'
import { message } from 'antd'
import { getRes } from './configFile';

interface PropsFromRedux extends ConnectedProps<typeof connector> { }

class App extends Component<PropsFromRedux> {
	async componentDidMount() {
		//发送请求检查用户登录状态
		try {
			const res = getRes(await checkSessionReq())
			if (res.message === 'sessionExist')
				this.props.loginSuccess(res.data.username, res.data.userID, res.data.userType)
		}
		catch (err) {
			message.error(err.toString())
		}
	}
	render() {
		return (
			<Frame>
				<Switch>
					{
						mainRoutes.map(item => {
							return (
								<Route
									key={item.path}
									path={item.path}
									exact={item.exact}
									render={
										(routerProps) => {
											return <item.component {...routerProps} key={routerProps.match.params.id || routerProps.match.params.view} />
										}
									} />
							)
						})
					}
					<Route component={NotFound} />
				</Switch>
			</Frame>
		)
	}
}

//connect加入props
const mapDispatchToProps = {
	loginSuccess
}

const connector = connect(null, mapDispatchToProps)

export default connector(App)